<script setup>
import { onBeforeMount, onMounted, useTemplateRef } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs';
import * as echarts from 'echarts/core';
import {
  CalendarComponent,
  VisualMapComponent,
  TooltipComponent,
} from 'echarts/components';
import { HeatmapChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { debounce } from 'lodash-es';

echarts.use([
  CalendarComponent,
  VisualMapComponent,
  TooltipComponent,
  HeatmapChart,
  CanvasRenderer,
]);

let chartInstance = null;
const chartRef = useTemplateRef('chart');
const chineseMonths = [
  '一月',
  '二月',
  '三月',
  '四月',
  '五月',
  '六月',
  '七月',
  '八月',
  '九月',
  '十月',
  '十一月',
  '十二月',
];

function transformData(data) {
  return data.map((item) => {
    return [item.date, item.count];
  });
}

async function renderChart() {
  if (!chartRef.value) return;
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  // 获取窗口宽度
  const windowWidth = window.innerWidth;
  const res = await axios.get('/api/gitee-contribution');
  if (res.data.length === 0) return;
  let range = [res.data[0].date, res.data[res.data.length - 1].date];
  if (windowWidth <= 688) {
    const now = dayjs();
    range = [
      `${now.subtract(4, 'month').format('YYYY-MM-DD')}`,
      now.format('YYYY-MM-DD'),
    ];
  }
  const data = transformData(res.data);
  chartInstance = echarts.init(chartRef.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: function (params) {
        // 确保数据格式正确
        if (Array.isArray(params.value)) {
          const date = params.value[0];
          const count = params.value[1] || 0;
          return `${count} 个贡献：${date}`;
        } else if (params.value) {
          // 处理非数组格式的数据
          return `${params.value} 个贡献：${params.name}`;
        }
        return `0 个贡献：${params.name}`;
      },
    },
    visualMap: {
      color: ['#17632a', '#34a550', '#50c36d', '#aeeebc', '#eff2f5'],
      min: 0,
      max: 10,
      show: false,
    },
    calendar: {
      left: 40,
      top: 30,
      cellSize: ['auto', 13],
      range,
      yearLabel: false,
      itemStyle: {
        borderWidth: 2,
        borderColor: '#faf8f1',
      },
      splitLine: {
        show: false,
      },
      dayLabel: {
        firstDay: 1,
        nameMap: ['周日', '周一', '', '', '周四', '', ''],
      },
      monthLabel: {
        formatter: function (params) {
          const now = new Date();
          const currentMonth = now.getMonth();
          const currentYear = now.getFullYear();
          if (
            Number(params.M) === currentMonth + 1 &&
            Number(params.yyyy) === currentYear
          ) {
            return '';
          } else {
            return chineseMonths[params.M - 1];
          }
        },
      },
    },
    series: {
      type: 'heatmap',
      coordinateSystem: 'calendar',
      data,
    },
  };
  chartInstance.setOption(option);
}

onMounted(() => {
  window.addEventListener('resize', debounce(renderChart, 100));
  renderChart();
});

onBeforeMount(() => {
  window.removeEventListener('resize', renderChart);
  chartInstance && chartInstance.dispose();
});
</script>

<template>
  <div class="gitee-contribution" ref="chart"></div>
</template>

<style scoped>
.gitee-contribution {
  height: 150px;
}
</style>
